<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use DB;

class CartController extends Controller
{
	public function index()
	{
        $config=DB::table('config')->get();
        // 获取某个用户的购物车数据让前台判断
        $count=DB::table('car')->where('uid','=',session()->get('homeuser')->id)->count();
        $data=DB::table('car')->join('goods','car.gid','=','goods.id')->where('uid','=',session()->get('homeuser')->id)->select('goods.goodname','goods.price','car.id','car.size')->get();
        return view('home.cart',['config'=>$config,'count'=>$count,'data'=>$data]);
   }
   // 添加商品到购物车
   public function store(Request $request)
   {
       $add=array('gid'=>$request->input('gid'),'num'=>$request->input('number'),'uid'=>session()->get('homeuser')->id,'size'=>$request->input('size'));
       $id=DB::table('car')->insertGetId($add);
       if ($id>0) {
           return back()->with('msg','添加成功!');
       }
   }
    // 删除购物车商品
	public function destroy($id)
	{
        $row = DB::table("car")->where("id",$id)->delete();
		if($row>0){
			return redirect("home1/cart");
		}else{
			return "删除失败";
    	}
    }
    public function deleteall()
    {
        $count=DB::table('car')->where('uid','=',session()->get('homeuser')->id)->count();
        if ($count>0) {
            $row=DB::table('car')->where('uid','=',session()->get('homeuser')->id)->delete();
        }
        $config=DB::table('config')->get();
        $count=DB::table('car')->where('uid','=',session()->get('homeuser')->id)->count();
        $data=DB::table('car')->join('goods','car.gid','=','goods.id')->where('uid','=',session()->get('homeuser')->id)->get();
        return view('home.cart',['config'=>$config,'count'=>$count,'data'=>$data]);
    }
    public function update(Request $request)
    {
        $car=DB::table('car')->where('uid','=',session()->get('homeuser')->id)->get()->toArray();
        for ($i=0; $i < count($car); $i++) {
            $data[$i]=$request->input('qty_item_'.($i+1));

            if ($data[$i]!=$car[$i]->num) {
                $e=array('num'=>$data[$i]);
                $id=DB::table('car')->where('id',$car[$i]->id)->update($e);
            }
        }
        return redirect('home1/corder');
    }
}
